package com.example.demo.User;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public Boolean addUser(User user) {
        // 执行插入操作
        String insertSql = "INSERT INTO users (id, name, password,identity) VALUES (?, ?, ?,?)";
        int rowsAffected = jdbcTemplate.update(insertSql, user.getId(), user.getName(), user.getPassword(),user.getIdentity());

        return rowsAffected > 0;
    }


    @Override
    public Boolean deleteUser(String userId, String password) {
        // 首先验证用户的ID和密码是否正确
        String checkSql = "SELECT COUNT(*) FROM users WHERE id = ? AND password = ?";
        Integer count = jdbcTemplate.queryForObject(checkSql, new Object[]{userId, password}, Integer.class);

        if (count == null || count == 0) {
            // 如果用户ID和密码不匹配，返回false
            System.out.println("用户ID或密码不正确，无法删除用户！");
            return false;
        }

        // 用户验证通过，执行删除操作
        String deleteSql = "DELETE FROM users WHERE id = ?";
        int rowsAffected = jdbcTemplate.update(deleteSql, userId);

        return rowsAffected > 0;
    }


    @Override
    public Boolean updateUser(User user) {
        String sql = "UPDATE users SET name = ? WHERE id = ?";
        return jdbcTemplate.update(sql, user.getName(), user.getId()) > 0;
    }

    @Override
    public List<User> findAllUser() {
        String sql = "SELECT * FROM users";
        return jdbcTemplate.query(sql, (rs, rowNum) -> {
            User user = new User();
            user.setId(rs.getString("id"));
            user.setName(rs.getString("name"));
            //user.setPassword(rs.getString("password"));
            return user;
        });
    }


    @Override
    public User findUserById(String id) {
        String sql = "SELECT * FROM users WHERE id = ?";
        try {
            return jdbcTemplate.queryForObject(sql, new Object[]{id}, (rs, rowNum) -> {
                User user = new User();
                user.setId(rs.getString("id"));
                user.setName(rs.getString("name"));
                user.setPassword(rs.getString("password"));
                user.setIdentity(rs.getString("identity"));
                return user;
            });
        } catch (EmptyResultDataAccessException e) {
            // 如果找不到对应的用户，返回 null
            return null;
        }
    }

    @Override
    public User authenticate(String name, String password) {
        try {
            // 查询用户信息
            String sql = "SELECT id, name, identity, password FROM users WHERE name = ?";
            User user = jdbcTemplate.queryForObject(
                    sql,
                    new Object[]{name},
                    (rs, rowNum) -> new User(
                            rs.getString("id"),
                            rs.getString("name"),
                            rs.getString("identity"),
                            rs.getString("password")
                    )
            );

            // 验证密码是否匹配
            if (user.getPassword().equals(password)) {
                // 密码匹配，返回用户信息（排除密码字段）
                return new User(user.getId(), user.getName(), user.getIdentity(),null);
            }

        } catch (EmptyResultDataAccessException e) {
            // 用户不存在时会抛出此异常
            return null;
        } catch (Exception e) {
            // 记录日志并处理其他异常
            System.err.println("登录错误: " + e.getMessage());
        }

        return null;
    }


    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    // 其他方法...


}
